package com.chris.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.chris.blog.entity.po.CommentPO;
import com.chris.blog.entity.po.QuestionCategoryPO;
import com.chris.blog.entity.po.QuestionPO;
import com.chris.blog.entity.po.UserPO;
import com.chris.blog.entity.vo.BlogWriteForm;
import com.chris.blog.service.*;
import com.chris.blog.util.SnowflakeIdWorker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
public class QuestionController {
    @Autowired
    QuestionCategoryService questionCategoryService;
    @Autowired
    QuestionService questionService;
    @Autowired
    CommentService commentService;
    @Autowired
    UserService userService;
    @Autowired
    FileUploadService fileUploadService;

    // 编辑一个新的问题 这是展示页
    @GetMapping("/question/write")
    public String toWrite(Model model) {
        // 查询所有问题的标签 放入
        List<QuestionCategoryPO> categoryList = questionCategoryService.selectAll();
        model.addAttribute("categoryList", categoryList);
        return "question/write";
    }

    /**
     * 问题列表展示请求
     */
    @GetMapping("/question")
    public String lists(Model model, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit) {
        // 默认一页显示10条数据 根据更新的时间来定
        PageHelper.startPage(page, limit);
        PageInfo<QuestionPO> info = new PageInfo<>(questionService.findAllDesc());
        model.addAttribute("info", info);
        List<QuestionCategoryPO> categories = questionCategoryService.selectAll();
        model.addAttribute("categoryList", categories);
        return "question/list";
    }

    @GetMapping("/question/read/{qid}")
    public String read(Model model, @PathVariable("qid") Long qid) {
        QuestionPO questionPO = questionService.findOneByQid(qid);
        // 每刷新一次 浏览量+1
        questionPO.setViews(questionPO.getViews() + 1);
        questionService.updateByPrimaryKeySelective(questionPO);
        model.addAttribute("question", questionPO);
        // 评论里的topic_id 对应的就是问题对象里的qid
        List<CommentPO> commentPOS = commentService.selectAllByTopic(qid);
        model.addAttribute("comments", commentPOS);
        return "question/read";
    }

    /**
     * 保存问题
     *
     * @param questionWriteForm
     * @return
     */
    @PostMapping("/question/write")
    public String save(BlogWriteForm questionWriteForm) {
        // 接受问题表单vo
        QuestionPO questionPO = new QuestionPO();
        Long qid = SnowflakeIdWorker.nextId();
        questionPO.setQid(qid);
        questionPO.setTitle(questionWriteForm.getTitle());
        questionPO.setContent(questionWriteForm.getContent());
        questionPO.setStatus(0);
        questionPO.setSort(0);
        questionPO.setViews(0);
        // 设置用户相关
        questionPO.setAuthorId(questionWriteForm.getAuthorId());
        questionPO.setAuthorAvatar(questionWriteForm.getAuthorAvatar());
        questionPO.setAuthorName(questionWriteForm.getAuthorName());
        // 设置栏目相关
        QuestionCategoryPO category = questionCategoryService.selectByPrimaryKey(questionWriteForm.getCategoryId());
        questionPO.setCategoryId(category.getId());
        questionPO.setCategoryName(category.getCategory());
        Date nowDate = new Date();
        questionPO.setGmtCreate(nowDate);
        questionPO.setGmtModified(nowDate);
        questionService.insertSelective(questionPO);

        return "redirect:/question/read/" + qid;

    }

    /**
     * 更新问题
     *
     * @param questionPO
     * @return
     */
    @PostMapping("/question/edit")
    public String update(QuestionPO questionPO) {
        Long qid = questionPO.getQid();
        QuestionPO queryQuestionPO = questionService.findOneByQid(qid);
        queryQuestionPO.setTitle(questionPO.getTitle());
        queryQuestionPO.setContent(questionPO.getContent());
        queryQuestionPO.setCategoryId(questionPO.getCategoryId());
        queryQuestionPO.setGmtModified(new Date());
        questionService.updateByPrimaryKeySelective(queryQuestionPO);
        return "redirect:/question/read/" + qid;
    }

    /**
     * 删除问题
     */
    @GetMapping("question/delete/{uid}/{qid}")
    public String delete(@PathVariable("uid") String uid,@PathVariable("qid") Long qid) {
        // 删除两张表的数据 问题表  评论表对应的都要删掉 评论就别删了 太麻烦了
        QuestionPO questionPO = questionService.findOneByQid(qid);
        UserPO userPO = userService.findUserByUid(uid);
        if (questionPO.getAuthorId().equals(uid) || userPO.getRoleId() == 1) {
            questionService.deleteByPrimaryKey(questionPO.getId());
            return "redirect:/question";
        } else {
            return "error/404";
        }

    }
    /**
     * 编辑问题
     */
    @GetMapping("question/edit/{uid}/{qid}")
    public String edit(Model model,@PathVariable("uid") String uid,@PathVariable("qid") Long qid) {
        // 根据qid 得到question对象 进行回显 同时标签集合也要传到前端
        // 只有该用户或者管理员可以进行修改
        UserPO userPO = userService.findUserByUid(uid);
        QuestionPO questionPO = questionService.findOneByQid(qid);
        if (questionPO.getAuthorId().equals(uid) || userPO.getRoleId() == 1) {
            model.addAttribute("question", questionPO);
            // 查询所有标签
            List<QuestionCategoryPO> categories = questionCategoryService.selectAll();
            model.addAttribute("categoryList", categories);
            return "question/edit";
        } else {
            return "error/404";
        }
    }

    /**
     *  发表评论 直接状态置为解决....
     *
     * @param qid
     * @param commentPO
     * @return
     */
    @PostMapping("/question/comment/{qid}")
    public String comment(@PathVariable("qid") Long qid, CommentPO commentPO) {
        Long commentId = SnowflakeIdWorker.nextId();
        commentPO.setCommentId(commentId);
        // 1为博客 2为问题
        commentPO.setTopicCategory(2);
        commentPO.setGmtCreate(new Date());
        commentService.insertSelective(commentPO);
        QuestionPO questionPO = questionService.findOneByQid(qid);
        questionPO.setStatus(1);
        questionService.updateByPrimaryKeySelective(questionPO);
        // 重定向到问题详情页
        return "redirect:/question/read/" + qid;
    }



    /**
     * 编辑器图片上传
     *
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/question/write/file/upload")
    @ResponseBody
    // editormd-image-file不可更改
    public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
        String upload = fileUploadService.upload(file);
        // 给editormd进行回调
        JSONObject res = new JSONObject();
        res.put("url", upload);
        res.put("success", 1);
        res.put("message", "upload success!");
        return res;
    }
}
